package kr.couponplay.android.activity.deal;

import java.util.List;

import kr.couponplay.android.activity.R;
import kr.couponplay.android.domain.BeanFactory;
import kr.couponplay.android.domain.deal.Deal;
import kr.couponplay.android.domain.deal.Qna;
import kr.couponplay.android.domain.deal.QnaBox;
import kr.couponplay.android.domain.deal.QnaDao;
import kr.couponplay.android.support.DisplayUtils;
import kr.couponplay.android.support.StringUtils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class DealDetailActivity extends Activity {
	private Context mContext = this;
	private List<QnaBox> qnaBoxList;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.deal_detail_activity);

		WebView image = (WebView)findViewById(R.id.deal_image);
		image.setFocusable(false);
		LayoutParams layoutParams = image.getLayoutParams();
		int width = DisplayUtils.widthPixels(this);
		layoutParams.width = width;
		layoutParams.height = (int)(width * 0.60);
		image.setLayoutParams(layoutParams);
		
		TextView title = (TextView) findViewById(R.id.detail_title);
		TextView originalPrice = (TextView) findViewById(R.id.detail_original_price);
		TextView salesPrice = (TextView) findViewById(R.id.detail_sales_price);
		TextView discountRate = (TextView) findViewById(R.id.detail_discount_rate);
		TextView nowCount = (TextView) findViewById(R.id.detail_now_count);
		TextView saleToDate = (TextView) findViewById(R.id.detail_sale_to_date);
		TextView providerName = (TextView) findViewById(R.id.detail_provider_name);
		TextView categoryName = (TextView) findViewById(R.id.detail_category_name);
					
		final Deal deal = (Deal)getIntent().getSerializableExtra("deal");
		
		if (image != null) {
			StringBuffer sb = new StringBuffer();
			sb.append("<html><body style='padding:0;margin:0;'>");
			sb.append("<img src='" + deal.getThumbnailImageUrl2() + "' style='width:100%;padding:0;margin:0' />");
			sb.append("</body></html>");
			image.loadDataWithBaseURL(null, sb.toString(), "text/html", "utf-8", null);
		}

		
		title.setText(deal.display1());
		originalPrice.setText(DisplayUtils.numFormat(deal.getOriginalPrice()) + "원");
		originalPrice.setPaintFlags(originalPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
		salesPrice.setText(DisplayUtils.numFormat(deal.getSalesPrice()) + "원");
		discountRate.setText(deal.getDiscountRate() + "%");
		nowCount.setText(DisplayUtils.numFormat(deal.getNowCount()) + "개");
		saleToDate.setText(DisplayUtils.dateFormat(Long.parseLong(deal.getToDate())) + " 까지");
		providerName.setText(deal.getProvider().getName());
		categoryName.setText(deal.getCategoryName());
		
		TextView joinExplain = (TextView)findViewById(R.id.join_explain);
		Button joinButton = (Button)findViewById(R.id.join_button);
		
		if (StringUtils.isEmpty(deal.getProvider().getJoinUrl())) {
			joinExplain.setVisibility(View.INVISIBLE);
			joinButton.setVisibility(View.INVISIBLE);
		} else {
			joinExplain.setVisibility(View.VISIBLE);
			joinExplain.setText("아직도 " + deal.getProvider().getName() + " 회원이 아니세요?");

			joinButton.setVisibility(View.VISIBLE);
			joinButton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Uri uri = Uri.parse(deal.getProvider().getJoinUrl());
					startActivity(new Intent(Intent.ACTION_VIEW, uri));
				}
			});
		}
        
        Button detailButton = (Button)findViewById(R.id.detail_button);
        detailButton.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		Uri uri = Uri.parse(deal.getDetailViewUrl());
        		startActivity(new Intent(Intent.ACTION_VIEW, uri));
        	}
        });
        
        getQnaList(deal);
    }

	private void drawQanBox() {
		if (qnaBoxList == null) {
			return;
		}
		
		LinearLayout qnaLayout = (LinearLayout)findViewById(R.id.qna_layout);
		
		for (QnaBox qnaBox : qnaBoxList) {
			LinearLayout.LayoutParams qnaBoxParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
			qnaBoxParams.setMargins(0, 0, 0, DisplayUtils.pixelFromDp(this, 5));

			LinearLayout qnaBoxLayout = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.qna_box_layout, null);
			qnaBoxLayout.setLayoutParams(qnaBoxParams);
			
			Qna question = qnaBox.getQuestion();
			LinearLayout questionView = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.qna_question, null);
			TextView qUserView = (TextView) questionView.findViewById(R.id.qna_question_user);
			TextView qContentView = (TextView) questionView.findViewById(R.id.qna_question_content);
			
			qUserView.setText(question.getUserName() + " (" + question.getRegisteDate() + ")");
			qContentView.setText(question.getContent());
			qnaBoxLayout.addView(questionView);
			
			for (Qna answer : qnaBox.getAnswers()) {
				LinearLayout.LayoutParams answerParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
				answerParams.setMargins(DisplayUtils.pixelFromDp(this, 15), DisplayUtils.pixelFromDp(this, 5), 0, 0);
				
				LinearLayout answerView = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.qna_answer, null);
				answerView.setLayoutParams(answerParams);
				
				TextView aUserView = (TextView) answerView.findViewById(R.id.qna_answer_user);
				TextView aContentView = (TextView) answerView.findViewById(R.id.qna_answer_content);
				
				aUserView.setText(answer.getUserName() + " (" + answer.getRegisteDate() + ")");
				aContentView.setText(answer.getContent());
				qnaBoxLayout.addView(answerView);				
			}
			qnaLayout.addView(qnaBoxLayout);
		}
		
		if (qnaBoxList != null && qnaBoxList.size() > 3) {
			LinearLayout questionMoreView = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.qna_question_more, null);
			qnaLayout.addView(questionMoreView);
		}
	}
	
	public void getQnaList(final Deal deal) {
		Thread thread = new Thread(new Runnable() {
            public void run() {
            	Message msg = Message.obtain();
            	try {
	            	String providerCode = deal.getProvider().getCode();
	        		String metaId = deal.getMetaId();
	        		msg.obj = BeanFactory.getBean(mContext.getApplicationContext(), QnaDao.class).selectList(deal.getId(), providerCode, metaId);
            	} catch (Exception e) {
            		msg.obj = e;
            	}
            	handler.sendMessage(msg);
            }
        });
        thread.start();
	}
	
	@SuppressLint("HandlerLeak") 
	private Handler handler = new Handler() {
	    @SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {
	    	if (msg.obj instanceof Throwable) {
	    		return;
	    	}
	    	
	    	qnaBoxList = (List<QnaBox>)msg.obj;
	    	drawQanBox();
	    }
	};	
}
